package com.iussoft.receiveData.interceptor;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import com.iussoft.receiveData.schedul.LogWritRunable;
import com.iussoft.receiveData.schedul.ScheduledDynamicTask;

/**
 * @description: 自定义过滤器
 * @author: Hou Dayu
 * @date: Created in 2020/4/8
 */
public class LogLevelFilter extends Filter<ILoggingEvent> {

    Level level;
    String modelType;//记录方式
    String logIndexName;

    public LogLevelFilter() {
    }

    /**
     * 返回值为DENY时，日志事件直接丢弃这条日志，不会再传递给剩下的过滤器。返回值为NEUTRAL时，则传递给下面的过滤器。返回值为ACCEPT时，日志事件立即处理这条日志，跳过调用其它过滤器
     */
    public FilterReply decide(ILoggingEvent event) {
        String msg = event.getMessage().trim();
        if(msg.startsWith("traceId = ") || msg.startsWith("processingStage = ") || msg.startsWith("exception = ")){
            if("manual".equalsIgnoreCase(modelType) && (Level.WARN.equals(event.getLevel()) || Level.ERROR.equals(event.getLevel()))){//开启线程写入日志
                String logs = event.getFormattedMessage();
                LogWritRunable run = new LogWritRunable(logs,event.getLevel().levelStr,logIndexName);
                ScheduledDynamicTask.getInstance().submitLog(run);
            }
            return FilterReply.DENY;
        } else if(msg.startsWith("receive_reqId = ") && Level.ERROR.equals(event.getLevel())){
            return FilterReply.ACCEPT;
        } else {
            return FilterReply.DENY;//忽略
        }
    }

    public void setLevel(Level level) {
        this.level = level;
    }

    public void start() {
        if (this.level != null) {
            super.start();
        }
    }

    public void setModelType(String modelType) {
        this.modelType = modelType;
    }

    public void setLogIndexName(String logIndexName) {
        this.logIndexName = logIndexName;
    }
}
